/*
 * Copyright (C) 2008 GeoScheduler Team, as stated on <http://www.geoscheduler.org/authors>.
 * 
 * This file is part of GeoScheduler.
 * 
 * GeoScheduler is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * GeoScheduler is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with GeoScheduler. If not, see <http://www.gnu.org/licenses/>.
 */
package org.geoscheduler.commons.qbuilder;

import java.util.Iterator;
import java.util.Map;

import org.geoscheduler.commons.qbuilder.TableDecl.ColumnDecl;

/**
 * FIXME [lko] comment me!
 *
 * @author lko
 */
public class UpdateSQLBuilder extends AbstractSQLBuilder<UpdateSQLBuilder> {

	public class UpdateValuesBuilder extends SQLValuesBuilder {
		public UpdateValuesBuilder(StringBuilder bld, EvalDelegate delegate) {
			super(bld, delegate);
		}

		public UpdateValuesBuilder nValue(ColumnDecl<?,?>... values) {
			return (UpdateValuesBuilder) super.nValue(values);
		}

		@Override
		public UpdateValuesBuilder nValue(Map<String, String> values) {
			return (UpdateValuesBuilder) super.nValue(values);
		}

		@Override
		public UpdateValuesBuilder value(Map<String, String> values) {
			return (UpdateValuesBuilder) super.value(values);
		}

		@Override
		public UpdateValuesBuilder nValue(String column, String name) {
			return (UpdateValuesBuilder) super.nValue(column, name);
		}

		@Override
		public UpdateValuesBuilder value(String column, String value) {
			return (UpdateValuesBuilder) super.value(column, value);
		}

		public WhereSQLBuilder where() {
			toString();
			append(" ");
			return new WhereSQLBuilder(builder());
		}
	}

	class Delegate implements SQLValuesBuilder.EvalDelegate {

		public void eval(StringBuilder bld, Map<String, String> pairs) {
			bld.append("SET ");
			for (Iterator<Map.Entry<String, String>> it = pairs.entrySet().iterator(); it.hasNext();) {
				Map.Entry<String, String> entry = it.next();
				bld.append(entry.getKey()).append("=").append(entry.getValue());
				if (it.hasNext()) {
					bld.append(",");
				}
			}
		}
	}

	public UpdateSQLBuilder() {
		this(new StringBuilder());
	}

	public UpdateSQLBuilder(StringBuilder bld) {
		super(bld);
		append("UPDATE ");
	}

	public UpdateValuesBuilder table(String table) {
		append(table).append(" ");
		return new UpdateValuesBuilder(builder(), new Delegate());
	}
}
